package com.zhangzhan.gulimallorder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhangzhan.gulimallcommcon.tos.MemberTo;
import com.zhangzhan.gulimallcommcon.util.MyCollUtil;
import com.zhangzhan.gulimallcommcon.util.PageUtils;
import com.zhangzhan.gulimallcommcon.util.Query;
import com.zhangzhan.gulimallorder.dao.OrderItemDao;
import com.zhangzhan.gulimallorder.entity.OrderEntity;
import com.zhangzhan.gulimallorder.entity.OrderItemEntity;
import com.zhangzhan.gulimallorder.interceptor.OrderInterceptor;
import com.zhangzhan.gulimallorder.service.OrderItemService;
import com.zhangzhan.gulimallorder.service.OrderService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service("orderItemService")
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Resource
    private OrderService orderService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils memberOrderItemList(Map<String, Object> params) {

        MemberTo member = OrderInterceptor.MEMBER.get();
        IPage<OrderEntity> page = orderService.page(
                new Query<OrderEntity>().getPage(params),
                Wrappers.<OrderEntity>lambdaQuery()
                        .eq(OrderEntity::getMemberId, member.getId())
        );
        List<OrderEntity> orders = page.getRecords();
        if (MyCollUtil.isNotEmpty(orders)) {
            orders.forEach(po->{
                List<OrderItemEntity> items = this.list(Wrappers.<OrderItemEntity>lambdaQuery()
                        .eq(OrderItemEntity::getOrderSn, po.getOrderSn()));
                po.setItems(items);
            });
        }


        return new PageUtils(page);
    }


}